package com.example.demo.sensitive.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.sensitive.dto.response.CheckResultResponse;
import lombok.Data;
import com.example.demo.sensitive.service.CheckResultService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.util.List;

/**
 * @ClassName ResultController
 * @Description 敏感词检查结果控制器
 * @Author System
 * @Date 2025/9/19
 **/
@RestController
@RequestMapping("/api/sensitive-results")
@Tag(name = "检查结果管理", description = "敏感词检查结果相关操作接口")
public class ResultController {

    @Resource
    private CheckResultService checkResultService;

    @GetMapping("/{taskId}")
    @Operation(summary = "分页查询检查结果", description = "根据条件分页查询检查结果列表")
    public Result<Page<CheckResultResponse>> getPageList(
            @Parameter(description = "任务ID") @PathVariable Long taskId,
            @Parameter(description = "当前页码") @RequestParam(defaultValue = "1") int current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "20") int size,
            @Parameter(description = "分类") @RequestParam(required = false) String category,
            @Parameter(description = "敏感等级") @RequestParam(required = false) Integer level,
            @Parameter(description = "处理状态") @RequestParam(required = false) String processStatus,
            @Parameter(description = "关键词") @RequestParam(required = false) String keyword) {
        
        Page<CheckResultResponse> result = checkResultService.getPageList(
                taskId, current, size, category, level, processStatus, keyword);
        return Result.success(result);
    }

    @GetMapping("/detail/{id}")
    @Operation(summary = "查询结果详情", description = "根据ID查询检查结果详情")
    public Result<CheckResultResponse> getById(
            @Parameter(description = "结果ID") @PathVariable Long id) {
        
        CheckResultResponse result = checkResultService.getById(id);
        return Result.success(result);
    }

    @GetMapping("/task/{taskId}/all")
    @Operation(summary = "查询任务所有结果", description = "查询指定任务的所有检查结果")
    public Result<List<CheckResultResponse>> getByTaskId(
            @Parameter(description = "任务ID") @PathVariable String taskId) {
        
        try {
            // 将字符串转换为Long，避免精度丢失
            Long taskIdLong = Long.valueOf(taskId);
            List<CheckResultResponse> result = checkResultService.getByTaskId(taskIdLong);
            return Result.success(result);
        } catch (NumberFormatException e) {
            throw new RuntimeException("任务ID格式错误: " + taskId);
        }
    }

    @GetMapping("/task/{taskId}/high-risk")
    @Operation(summary = "查询高风险结果", description = "查询指定任务的高风险检查结果")
    public Result<List<CheckResultResponse>> getHighRiskResults(
            @Parameter(description = "任务ID") @PathVariable Long taskId) {
        
        List<CheckResultResponse> result = checkResultService.getHighRiskResults(taskId);
        return Result.success(result);
    }

    @PostMapping("/{id}/ignore")
    @Operation(summary = "忽略结果", description = "将检查结果标记为忽略")
    public Result<String> ignoreResult(
            @Parameter(description = "结果ID") @PathVariable Long id,
            @Parameter(description = "处理说明") @RequestParam(required = false) String note) {
        
        checkResultService.ignoreResult(id, note);
        return Result.success("结果已忽略", "success");
    }

    @PostMapping("/batch-ignore")
    @Operation(summary = "批量忽略结果", description = "批量将检查结果标记为忽略")
    public Result<String> batchIgnore(
            @RequestBody BatchProcessRequest request) {
        
        checkResultService.batchIgnore(request.getIds(), request.getNote());
        return Result.success("批量忽略成功", "success");
    }

    @PostMapping("/{id}/confirm")
    @Operation(summary = "确认结果", description = "确认检查结果为真实敏感内容")
    public Result<String> confirmResult(
            @Parameter(description = "结果ID") @PathVariable Long id,
            @Parameter(description = "处理说明") @RequestParam(required = false) String note) {
        
        checkResultService.confirmResult(id, note);
        return Result.success("结果已确认", "success");
    }

    @PostMapping("/{id}/generate-clean-sql")
    @Operation(summary = "生成清理SQL", description = "为检查结果生成数据清理SQL")
    public Result<String> generateCleanSQL(
            @Parameter(description = "结果ID") @PathVariable Long id,
            @Parameter(description = "清理动作") @RequestParam String action) {
        
        String sql = checkResultService.generateCleanSQL(id, action);
        return Result.success(sql);
    }

    @PostMapping("/batch-generate-clean-sql")
    @Operation(summary = "批量生成清理SQL", description = "批量生成数据清理SQL")
    public Result<List<String>> batchGenerateCleanSQL(
            @RequestBody BatchCleanRequest request) {
        
        List<String> sqls = checkResultService.batchGenerateCleanSQL(request.getIds(), request.getAction());
        return Result.success(sqls);
    }

    @PostMapping("/execute-clean")
    @Operation(summary = "执行清理SQL", description = "执行数据清理SQL语句")
    public Result<Integer> executeCleanSQL(
            @RequestBody ExecuteCleanRequest request) {
        
        Integer affectedRows = checkResultService.executeCleanSQL(request.getSql(), request.getOptions());
        return Result.success("执行成功", affectedRows);
    }

    @GetMapping("/task/{taskId}/statistics")
    @Operation(summary = "结果统计", description = "获取指定任务的结果统计信息")
    public Result<CheckResultService.ResultStatistics> getResultStatistics(
            @Parameter(description = "任务ID") @PathVariable Long taskId) {
        
        CheckResultService.ResultStatistics result = checkResultService.getResultStatistics(taskId);
        return Result.success(result);
    }

    @GetMapping("/task/{taskId}/table-statistics")
    @Operation(summary = "表列统计", description = "获取指定任务按表列的统计信息")
    public Result<List<CheckResultService.TableColumnStatistics>> getTableColumnStatistics(
            @Parameter(description = "任务ID") @PathVariable Long taskId) {
        
        List<CheckResultService.TableColumnStatistics> result = checkResultService.getTableColumnStatistics(taskId);
        return Result.success(result);
    }

    @GetMapping("/{taskId}/export")
    @Operation(summary = "导出检查结果", description = "导出检查结果到Excel文件")
    public ResponseEntity<byte[]> exportResults(
            @Parameter(description = "任务ID") @PathVariable Long taskId,
            @Parameter(description = "导出格式") @RequestParam(defaultValue = "excel") String format) {
        
        byte[] data = checkResultService.exportResults(taskId, format);
        
        String filename = "check_results_" + taskId + ".xlsx";
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(data);
    }

    @DeleteMapping("/task/{taskId}")
    @Operation(summary = "清理任务结果", description = "删除指定任务的所有检查结果")
    public Result<String> cleanTaskResults(
            @Parameter(description = "任务ID") @PathVariable Long taskId) {
        
        checkResultService.cleanTaskResults(taskId);
        return Result.success("结果清理成功", "success");
    }

    @DeleteMapping("/expired")
    @Operation(summary = "清理过期结果", description = "清理指定天数之前的检查结果")
    public Result<Integer> cleanExpiredResults(
            @Parameter(description = "保留天数") @RequestParam(defaultValue = "30") int days) {
        
        Integer count = checkResultService.cleanExpiredResults(days);
        return Result.success("清理完成", count);
    }

    /**
     * 批量处理请求
     */
    @Data
    public static class BatchProcessRequest {
        private List<Long> ids;
        private String note;
    }

    /**
     * 批量清理请求
     */
    @Data
    public static class BatchCleanRequest {
        private List<Long> ids;
        private String action;
    }

    /**
     * 执行清理请求
     */
    @Data
    public static class ExecuteCleanRequest {
        private String sql;
        private ExecuteOptions options;
    }

    /**
     * 执行选项
     */
    @Data
    public static class ExecuteOptions {
        private Boolean dryRun = false;
        private Integer maxAffectedRows = 1000;
    }
}
